package gwt.trading.client;

import gwt.trading.client.util.Closure;
import gwt.trading.client.util.GwtList;

import com.google.gwt.core.client.GWT;

/**
 * @author Iulian Costan (iulian.costan@gmail.com)
 *
 */
public class StockQuoteList {

	private GwtList /* <StockQuote> */quotes;

	public void init(StockQuote[] quotes) {
		this.quotes = new GwtList(quotes);
	}

	public float getHighest() {
		HighestFinder finder = new HighestFinder();
		float highest = finder.getHighest();
		GWT.log("highest: " + highest, null);
		return highest;
	}

	public float getLowest() {
		LowestFinder finder = new LowestFinder();
		float lowest = finder.getLowest();
		GWT.log("lowest: " + lowest, null);
		return lowest;
	}

	public float getMaxVolume() {
		VolumeFinder finder = new VolumeFinder();
		float maxVolume = finder.getMaxVolume();
		GWT.log("max volume: " + maxVolume, null);
		return maxVolume;
	}

	public int getLength() {
		return quotes.getLength();
	}

	private class VolumeFinder {

		private long volume;

		public VolumeFinder() {
			quotes.forAll(new Closure() {

				public void execute(Object object) {
					StockQuote quote = (StockQuote) object;
					if (quote.getVolume() > volume) {
						volume = quote.getVolume();
					}
				}
			});
		}

		public float getMaxVolume() {
			return volume;
		}
	}

	private class HighestFinder {

		private float highest;

		public HighestFinder() {
			quotes.forAll(new Closure() {

				public void execute(Object object) {
					StockQuote quote = (StockQuote) object;
					if (quote.getHigh() > highest) {
						highest = quote.getHigh();
					}
				}
			});
		}

		public float getHighest() {
			return highest;
		}
	}

	private class LowestFinder {

		private float lowest = Float.MAX_VALUE;

		public LowestFinder() {
			quotes.forAll(new Closure() {

				public void execute(Object object) {
					StockQuote quote = (StockQuote) object;
					if (quote.getLow() < lowest) {
						lowest = quote.getLow();
					}
				}
			});
		}

		public float getLowest() {
			return lowest;
		}
	}

	public GwtList getQuotes() {
		return quotes;
	}

}
